package com.yc.baseProgram.recursion;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * description: 笛卡尔积（for循环-指针式）
 * author: yc
 * date: 2021/2/24 8:54
 */
public class C2 {



    public List<String> m1(String[][] s) {
        List<String> res = new ArrayList<>();//结果
        int sl = s.length;//外层长度
        int[] table = new int[sl];//一个和外层长度一样的刻度表格，用于记录每个“内集合”的指针位置

        int[] tableMax = new int[sl];//记录每个内集合的长度，也就是刻度表的最大值+1
        for(int i=0; i<s.length; i++) {
            tableMax[i] = s[i].length;
        }


        int m = 0;//试图输出100次(防止死循环)
        while (m < 100) {
            m++;
            StringBuffer sb = new StringBuffer();
            //输出
            for (int i=0; i<sl; i++) {
                if (i != 0) {
                    sb.append(",");
                }
                sb.append(s[i][table[i]]);
            }
            res.add(sb.toString());

            //刷新指针(从后往前调)
            boolean add = false;//进位标记
            for (int i=table.length-1; i>=0; i--) {
                table[i]++;
                if (i == table.length-1) {
                    if (table[i] == tableMax[i]) {
                        table[i] = 0;
                        add = true;
                    } else {
                        break;
                    }
                } else {
                    if (add) {
                        if (table[i] == tableMax[i]) {
                            table[i] = 0;
                        } else {
                            add = false;
                            break;
                        }
                    } else {
                        break;
                    }
                }

            }

            if (add) {
               break;
            }

        }

        return res;

    }

    public static void main(String[] args) {
        String[][] s = {{"1","2","3"},{"a","b","c"},{"@","#","$"}};
        C2 c2 = new C2();
        System.out.println(c2.m1(s));
    }

}
